#include "CDialogBar.h"

CDialogBar::CDialogBar(QWidget *parent) : CBaseTitleBar(parent) {
    init();
}

CDialogBar::~CDialogBar() {
}

void CDialogBar::init() {
    setAttribute(Qt::WA_StyledBackground);

    m_titleVisible = true;

    m_closeButton = new CToolButton();
    m_closeButton->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);

    m_closeButton->setObjectName("win-close-button");
    m_closeButton->setCursor(QCursor(Qt::PointingHandCursor));

    m_spacerLeft = new QSpacerItem(40, 20, QSizePolicy::MinimumExpanding, QSizePolicy::Minimum);

    m_layout = new QHBoxLayout();
    m_layout->setMargin(0);
    m_layout->setSpacing(0);
    m_layout->addItem(m_spacerLeft);
    m_layout->addWidget(m_closeButton);

    setLayout(m_layout);

    connect(m_closeButton, &QAbstractButton::clicked, this, &CDialogBar::handleClose);
    connect(this, &QWidget::windowTitleChanged, this, &CDialogBar::handleWindowTitleChanged);
}

bool CDialogBar::isMouseFree() const {
    QPoint pos = mapFromGlobal(QCursor::pos());
    QWidget *w = childAt(pos);
    if ((!w && rect().contains(pos))) {
        return true;
    }
    return false;
}

bool CDialogBar::titleVisible() const {
    return m_titleVisible;
}

void CDialogBar::setTitleVisible(bool titleVisible) {
    m_titleVisible = titleVisible;
    update();
}

void CDialogBar::handleClose() {
    emit closeRequested();
}

void CDialogBar::handleWindowTitleChanged(const QString &title) {
    update();
}

void CDialogBar::updateBarVisible() {
    m_closeButton->setVisible(m_barVisible);
}
